
import { useWebSocket } from '@vueuse/core'

class Socket {

    onConnected: any = () => { }
    onDisconnected: any = () => { }
    onMessage: any = () => { }
    fn: any = () => { }
    status: 1 | 0 = 0 // 0:断开 1:连接
    socketKey: number = 0 // 凭证

    init = () => {
        this.fn = useWebSocket('ws://127.0.0.1:1912', {
            onConnected: (ws) => {
                // console.log('websocket 连接成功！', ws)
                this.onConnected(ws)
                this.status = 1
            },
            onDisconnected: (ws, event) => {
                // console.log('websocket 断开连接！', ws, event)
                this.onDisconnected(ws, event)
                this.status = 0
            },
            onError: (ws, event) => {
                // console.log('websocket 出错！', ws, event)
                this.onDisconnected(ws, event)
                this.status = 0
            },
            onMessage: (ws, event) => {
                // console.log('websocket get message:', ws, event)
                this.onMessage(ws, event)
            },
            heartbeat: false,
            autoReconnect: {
                retries: Infinity,
                delay: 5000,
                onFailed: () => {
                    this.onDisconnected()
                },
            },
        })
    }

    close = () => {
        this.fn.close()
        this.fn = null
    }

    updateSocketKey = (key: number) => {
        this.socketKey = key
    }

    send = (data = {}) => {
        if (this.status === 1) {
            this.fn.send(JSON.stringify(data))
        }
    }

    constructor(params = {}) {
        Object.assign(this, params)
        this.init()
    }
}

export {
    Socket
}